<template>
  <el-container>
    <el-header class="height_auto">
      <form-panel
        :formid="searchFormId"
        :templet="searchTemplet"
        form-type="query"
        :form-cols="settings.queryFormCols"
        v-show="searchFormId != null || searchTemplet != null"
        ref="searchfrom"
        :remote="remotFunc"
      >
        <template slot="cfg_buttonArray">
          <vxe-button size="mini" status="primary" content="搜索" @click="search" style="margin-left:12px;"></vxe-button>
          <vxe-button size="mini" content="重置" @click="resetSearch"></vxe-button>
        </template>

      </form-panel>
    </el-header>
    <el-main class="el_padding">
      <div class="bk_gridtable">
        <vxe-grid
          :id="settings.id"
          :ref="xGrid"
          :resizable="settings.resizable"
          :border="settings.border"
          :loading="loading"
          :export-config="settings.exportConfig"
          :data="tableData"
          :align="settings.allAlign"
          :columns="settings.tableColumn"
          :height="settings.height"
          :max-height="settings.maxHeight"
          :auto-resize="settings.autoResize"
          :sync-resize="settings.syncResize"
          :stripe="settings.stripe"
          :round="settings.round"
          :size="settings.size"
          :header-align="settings.headerAlign"
          :footer-align="settings.footerAlign"
          :show-header="settings.showHeader"
          :highlight-current-row="settings.highlightCurrentRow"
          :highlight-hover-row="settings.highlightHoverRow"
          :highlight-current-column="settings.highlightCurrentColumn"
          :highlight-hover-column="settings.highlightHoverColumn"
          :highlight-cell="settings.highlightCell"
          :row-class-name="settings.rowClassName"
          :cell-class-name="settings.cellClassName"
          :header-row-class-name="settings.headerRowClassName"
          :header-cell-class-name="settings.headerCellClassName"
          :footer-row-class-name="settings.footerRowClassName"
          :footer-cell-class-name="settings.footerCellClassName"
          :cell-style="settings.cellStyle"
          :header-cell-style="settings.headerCellStyle"
          :footer-cell-style="settings.footerCellStyle"
          :row-style="settings.rowStyle"
          :header-row-style="settings.headerRowStyle"
          :footer-row-style="settings.footerRowStyle"
          :show-footer="settings.showFooter"
          :footer-method="settings.footerMethod"
          :merge-cells="settings.mergeCells"
          :merge-footer-items="settings.mergeFooterItems"
          :span-method="settings.spanMethod"
          :footer-span-method="settings.footerSpanMethod"
          :show-overflow="settings.showOverflow"
          :show-header-overflow="settings.showHeaderOverflow"
          :show-footer-overflow="settings.showFooterOverflow"
          :column-key="settings.columnKey"
          :row-key="settings.rowKey"
          :keep-source="settings.keepSource"
          :z-index="settings.zIndex"
          :column-config="settings.columnConfig"
          :seq-config="settings.seqConfig"
          :sort-config="settings.sortConfig"
          :filter-config="settings.filterConfig"
          :import-config="settings.importConfig"
          :print-config="settings.printConfig"
          :radio-config="settings.radioConfig"
          :checkbox-config="settings.checkboxConfig"
          :tooltip-config="settings.tooltipConfig"
          :tree-config="settings.treeConfig"
          :context-menu="settings.contextMenu"
          :keyboard-config="settings.keyboardConfig"
          :edit-config="settings.editConfig"
          :valid-config="settings.validConfig"
          :edit-rules="settings.editRules"
          :empty-render="settings.emptyRender"
          :custom-config="settings.customConfig"
          :animat="settings.animat"
          :cloak="settings.cloak"
          :delay-hover="settings.delayHover"
          :scroll-x="settings.scrollX"
          :scroll-y="settings.scrollY"
          :params="settings.params"
          :form-config="settings.formConfig"
          :pager-config="settings.pagerConfig"
          :proxy-config="settings.proxyConfig"
          :zoom-config="settings.zoomConfig"
          @toolbar-button-click="toolbarButtonClickEvent"
          @checkbox-change="checkboxChange"
          @cell-dblclick="dblclick"
          @cell-click="celick"
          @page-change="pageChange"
          @custom="customHandler"
        >
          <vxe-toolbar
            v-show="settings.tableToolbar"
            slot="toolbar"
            :custom="settings.tableToolbar && settings.tableToolbar.custom"
            :zoom="settings.tableToolbar && settings.tableToolbar.zoom"
            :refresh="settings.tableToolbar && settings.tableToolbar.refresh"
            :print="settings.tableToolbar && settings.tableToolbar.print"
            :export="!1"
        
          >
            <!--工具条开始-->
            <template
              v-for="(item, index) in settings.tableToolbar
                ? settings.tableToolbar.buttons
                : []"
            >
              <span
                v-if="item.isSlot"
                slot="buttons"
                :key="index"
                class="vxe-button"
                ><slot :name="item.name"
              /></span>
              <vxe-button
                v-else
                slot="buttons"
                :key="index"
                :icon="item.icon"
                :name="item.name"
                @click="item.handler"
                >{{ item.name }}
                <template
                  v-show="item.dropdowns"
                  slot="dropdowns"
                  v-for="(dropbtn, i2) in item.dropdowns"
                >
                  <vxe-button
                    :type="dropbtn.type"
                    :disabled="dropbtn.disabled"
                    :key="i2"
                    :name="dropbtn.name"
                    @click="dropbtn.handler"
                    >{{ dropbtn.name }}
                  </vxe-button>
                </template>
              </vxe-button>
            </template>
            <template
              v-for="(item, index) in settings.tableToolbar
                ? settings.tableToolbar.tools
                : []"
            >
              <span
                v-if="item.isSlot"
                slot="tools"
                :key="index"
                class="bk_tools"
                ><slot :name="item.name"
              /></span>
              <vxe-button
                v-else
                :key="index"
                slot="tools"
                @click="item.handler"
              >
                {{ item.name }}
                <template
                  v-show="item.dropdowns"
                  slot="dropdowns"
                  v-for="(dropbtn, i2) in item.dropdowns"
                >
                  <vxe-button
                    :type="dropbtn.type"
                    :disabled="dropbtn.disabled"
                    :key="i2"
                    @click="dropbtn.handler"
                    >{{ dropbtn.name }}
                  </vxe-button>
                </template>
              </vxe-button>
            </template>
          </vxe-toolbar>
          <!--工具条结束-->
          <template v-slot:operate="{ row }">
            <slot name="tableButton" :row="row"></slot>
          </template>
        </vxe-grid>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import formPanel from "@/components/formpanel";
import SnowflakeId from "snowflake-id";
import Sortable from "sortablejs";
import "font-awesome/css/font-awesome.min.css";
import XEUtils from "xe-utils";
import request from "@/utils/requestutil";
import {fileDownload} from "@/utils/httpRequet"
export default {
  name: "GirdPage",
  props: {
    config: {
      type: Object,
      default: () => {
        return {};
      }
    },
    beforeSearch:{type:Function,default:()=>{return {}}}
  },
  components: {
    formPanel
  },
  data() {
    return {
      searchFormId: null,
      searchTemplet: null,
      xGrid: "grid_" + this.guid(),
      refreshpage: false,
      remotFunc:{},
      options: {
        treeConfigKey: "",
        checkType: "radio", //check // no
        isEdit: false, //是否行内编辑
        isIndex: false, //是否有索引
        isSort: false, //是否拖拽排
        isRemotePage: false,
        tableToolbar: {},
        shieldBtn: false,
        useDefaultButtons: false
      },
      // 属性配置
      settings: {
        templateCfgUrl: "gridColumncfg",
        dataUrl: "gridDataUrl",
        templet: null,
        hasFixed: true,
        sortable: false,
        flag: null,
        id: this.guid(),
        resizable: true, // 所有列是否允许拖动列宽调整大小
        hideToolBar: false,
        queryTemplet: null,
        queryFormCols: "4",
        tableToolbar: {
          export: false,
          custom: true,
          tools: [],
          buttons: [
            { code: "insert_actived", name: "新增", icon: "fa fa-plus" },
            { code: "delete", name: "直接删除", icon: "fa fa-trash-o" },
            { code: "mark_cancel", name: "删除/取消", icon: "fa fa-trash-o" },
            {
              code: "save",
              name: "保存",
              icon: "fa fa-save",
              status: "success"
            }
          ],
          refresh: true,
          import: false,
          print: false,
          zoom: true
        },
        tableColumn: [],
        exportConfig: {
          type: "xlsx",
          types: ["xlsx", "csv", "html", "xml", "txt"],
          modes: ["current", "all"],
          remote: true,
          exportMethod: this.remoteExportMethod
        }, // 导出配置项
        allAlign: "left", // //所有的列对齐方式String left（左对齐）, center（居中对齐）, right（右对齐）
        height: 1000,
        maxHeight: 1000,
        autoResize: false, // 是否自动监听父容器变化去更新响应式表格宽高
        syncResize: false, // 是否自动根据状态属性去更新响应式表格宽高
        stripe: true, // 是否带有斑马纹
        round: true, // 是否圆角边框
        size: "mini", // 表格的尺寸
        loading: "loading", // 表格是否显示加载中boolean
        // 是否带有边框
        border: true,
        // 所有的表头列的对齐方式 left（左对齐）, center（居中对齐）, right（右对齐）
        headerAlign: "left",
        // 所有的表尾列的对齐方式
        footerAlign: "left",
        // 是否显示表头
        showHeader: true,
        // 是否要高亮当前选中行
        highlightCurrentRow: true,
        // 鼠标移到行是否要高亮显示
        highlightHoverRow: true,
        // 是否要高亮当前选中列
        highlightCurrentColumn: false,
        // 鼠标移到列是否要高亮显示
        highlightHoverColumn: false,
        // 激活单元格编辑时是否高亮显示
        highlightCell: false,
        // 是否显示表尾合计
        showFooter: false,
        // 表尾合计的计算方法
        footerMethod: this.footerMethodExtends,
        // 给行附加 className
        rowClassName: "",
        // 给单元格附加 className
        cellClassName: "",
        // 给表头的行附加 className
        headerRowClassName: "",
        // 给表头的单元格附加 className
        headerCellClassName: "",
        // 给表尾的行附加 className
        footerRowClassName: "",
        // 给表尾的单元格附加 className
        footerCellClassName: "",
        // 给单元格附加样式
        cellStyle: {},
        // 给表头单元格附加样式
        headerCellStyle: {},
        // 给表尾单元格附加样式
        footerCellStyle: {},
        // 给行附加样式
        rowStyle: {},
        // 给表头行附加样式
        headerRowStyle: {},
        // 给表尾行附加样式
        footerRowStyle: {},
        // 合并行或列
        spanMethod: this.spanMethodExtends,
        // 表尾合并行或列
        footerSpanMethod: this.footerSpanMethodExtends,
        // 设置所有内容过长时显示为省略号  ellipsis（只显示省略号）,title（并且显示为原生 title）,tooltip（并且显示为 tooltip 提示）
        showOverflow: "title",
        // 设置表头所有内容过长时显示为省略号
        showHeaderOverflow: "title",
        // 设置表尾所有内容过长时显示为省略号
        showFooterOverflow: "title",
        // 所有列宽度
        columnWidth: "20%",
        // 所有列最小宽度，把剩余宽度按比例分配
        columnMinWidth: "20%",
        // 主键配置
        columnKey: false,
        rowKey: false,
        zIndex: 999,
        keepSource: false,
        // 序号配置项
        seqConfig: {
          startIndex: 100
        },
        // 排序配置项
        sortConfig: {
          trigger: "cell", // 所有列是否使用服务端排序，如果设置为 true 则不会对数据进行处理
          remote: true
        },
        // 筛选配置项
        filterConfig: {
          remote: true // 删选为远程删选
        },
        // 单选框配置
        radioConfig: {
          // labelField: 'id', // 单选框显示的字段名，可以直接显示在单选框中
          reserve: true, // 是否保留勾选状态，对于某些场景下非常有用，比如数据被刷新之后还保留之前选中的状态（需要有 row-id）
          highlight: true
        },
        // 复选框配置项
        checkboxConfig: {
          // labelField: 'id', //
          reserve: true, //
          highlight: true, //
          range: true //
        },
        // tooltip 配置项
        tooltipConfig: {
          enabled: true,
          theme: "light", // dark
          enterable: true,
          leaveDelay: 500,
          contentMethod: this.contentMethodExtends
        },
        // 导入配置项
        importConfig: {
          remote: true,
          importMethod: this.importMethodExtends,
          types: ["xlsx", "csv", "txt"], // ['csv', 'html', 'xml', 'txt']
          modes: ["insert"] // covering 覆盖,insert 插入
        },
        // 打印配置项
        printConfig: {
          sheetName: "文档页",
          mode: "current", // 输出数据的方式 ,current
          modes: ["current", "selected", "all"]
        },
        // 树形结构配置项
        treeConfig: false,
        // 快捷菜单配置项
        contextMenu: false,
        // 按键配置项
        keyboardConfig: {
          isArrow: true, // 开启方向键
          isDel: true // 删除按钮
        },
        // 单击编辑,单元格
        editConfig: {
          // trigger: "click",
          // mode: "row",
          showStatus: true,
          activeMethod: this.activeCellMethod,
          showIcon: false, //取消表头图标
          showAsterisk: false //*取消
        },
        // 校验配置项
        validConfig: {}, // 后面在补充
        // 校验规则配置项
        editRules: {}, // 后面在补充
        // 自定义列配置项
        customConfig: {
          mainObject: this,
          storage: true,
          checkMethod: this.checkColumnMethodExtends
        },
        // 横向虚拟滚动配置项（注：当 tree-config 启用后纵向虚拟滚动将无效）
        scrollX: {
          gt: 60, // 指定大于指定行时自动启动纵向虚拟滚动，如果为 0 则总是启用，如果为 -1 则关闭（注：启用纵向虚拟滚动之后将不能支持动态行高）
          oSize: 0 // 指定每次渲染的数据偏移量，偏移量越大渲染次数就越少，但每次渲染耗时就越久（对于古董级的低性能浏览器可以设置大一点）
        },
        // 纵向虚拟滚动配置（注：当 tree-config 启用后纵向虚拟滚动将无效）
        scrollY: {
          gt: 100, // 指定大于指定行时自动启动纵向虚拟滚动，如果为 0 则总是启用，如果为 -1 则关闭（注：启用纵向虚拟滚动之后将不能支持动态行高）
          oSize: 0 // 指定每次渲染的数据偏移量，偏移量越大渲染次数就越少，但每次渲染耗时就越久（对于古董级的低性能浏览器可以设置大一点）
        },
        // 优化相关
        cloak: false,
        animat: true,
        delayHover: 250, // 当表格发生拖动、滚动...等行为时，至少多少毫秒之后才允许触发 hover 事件
        // 额外的参数
        params: {},
        queryParam: {},
        formConfig: {
          items: []
        },
        pagerConfig: {
          pageSize: 20,
          total: undefined,
          pagerCount: 7,
          pageSizes: [10, 20, 40, 50, 100],
          align: undefined
        },
        // 查询代理
        proxyConfig: {
          autoLoad: false,
          seq: true, // 启用动态序号代理
          sort: true, // 启用排序代理
          filter: true, // 启用筛选代理
          form: false, // 开启form表单模式
          ajax: {
            query: ({ $grid, page, sort, filters, form, params }) => {
              let settings = this.settings;
              let sortConfig=settings.sortConfig||{};
              sort=Object.assign({},sortConfig.defaultSort,sort);
             
              const{userSetPage}=$grid.pagerConfig;
              if(userSetPage){
                if(userSetPage.currentPage!=undefined){
                  page.currentPage=userSetPage.currentPage
                }
                if(userSetPage.pageSize!=undefined && userSetPage.pageSize !=page.pageSize){
                  page.pageSize=userSetPage.pageSize;
                  page.currentPage=1;
                }
                $grid.pagerConfig.userSetPage=undefined;
              }
              let $t = this;
              let main = $grid.customConfig.mainObject;
              // 处理排序条件
              let searchdata = main.getSearchData();
              let _queryParams="TEMPLET";
              
              if(main.queryParams){
                _queryParams = "FORM";
                searchdata = Object.assign(searchdata,main.queryParams);
              //  main.queryParams=undefined;
              }
              const queryParams = Object.assign(
                {
                  orderField: sort.property||sort.field,
                  order: sort.order,
                  page: page.currentPage,
                  pageRows: page.pageSize,
                  isInit: page.currentPage == 1 || main.refreshpage
                },
                this.tableForm,
                settings.params,
                main.queryParams
              );
              // var promise =  XEAjax.get(`https://api.xuliangzhan.com:10443/api/pub/page/list/${page.pageSize}/${page.currentPage}`, queryParams)
              // console.log(queryParams)
              if(main.settings.beforeLoad){
                 searchdata=main.settings.beforeLoad(searchdata);
              }
               let voParam = { ...searchdata };
              this.$_.extend(
                voParam,
                this.tableForm,
                settings.params,
                main.queryParams
              );
              $t.queryPageInfo = $t.queryPageInfo || {};
              $t.queryPageInfo.currentPage = page.currentPage;
              return new Promise((resolve, reject) => {
                // if (this.settings.templet) {
                  request({
                    url: this.settings.dataUrl,
                    data: {flag:this.settings.flag,templet: this.settings.templet, ...queryParams,queryParams:_queryParams},
                    voParam: voParam,
                    method: "post"
                  })
                    .then(response => {
                      response = response.obj || response;
                      let page = $t.queryPageInfo;
                      if (response.page) {
                        page = {
                          pageSize: response.page.pageRows,
                          currentPage: response.page.page,
                          total: parseInt(response.page.total)
                        };
                      }
                      main.refreshpage = false;
                      $t.queryPageInfo = page;
                      const temp = {
                        page: page,
                        result: response.data
                      };
                      //   let g=$t.$refs[$t.xGrid]
                      //  // g.loadData(response.data)
                      //  // g.pagerConfig={}
                      //   window.grid=$t.$refs[$t.xGrid]
                      // console.log(temp)
                      resolve(temp);
                      $t.$emit("afterload",temp)
                    })
                    .catch(response => {
                      reject(response);
                    });
                // }
              });
            }
            // delete: ({ body }) => XEAjax.post('https://api.xuliangzhan.com:10443/api/pub/save', body),
            // save: ({ body }) => XEAjax.post('https://api.xuliangzhan.com:10443/api/pub/save', body)
          }
        }
      },
      // 是否显示异步加载
      loading: false,
      tableData: [],
      tableForm: {} // form表单为空
    };
  },
  watch: {
    config: {
      // 对传递过来的数据进行监听, 如果父组件数据发生改动,子组件对应发生变化
      handler(val, oldVal) {
        this.initGriData(val);
        // 初始化表头以及查询项数据
        this.getTableColumn(true);
      },
      deep: true,
      immediate: true
    }
  },

  created() {
    this.settings;
  },
  mounted() {
    
  },
  methods: {
    //自定义按钮事件
    customHandler({type, $table,  $grid, $event }){
      window.sq=$grid;
      if(type=='reset'){
        request({
          url:'clearUserGridVisableColumn',
          data:{templet:this.settings.templet,type:'table'},
          method:"post"
        }).then(res=>{
          if(res.result=="SUCCESS"){
            this.$message({message:"保存成功",type:'success'});
            this.getTableColumn(true);
          }
        })
      }else if(type=="confirm"){
        let column=$grid.getTableColumn().visibleColumn;
        let tem=[];
        for(let i=0;i<column.length;i++){
          tem.push(column[i].property)
        }
        request({
          url:'saveUserGridVisableColumn',
          data:{templet:this.settings.templet,fields:tem.join(","),type:'table'},
          method:"post"
        }).then(res=>{
         if(res.result=="SUCCESS"){
            this.$message({message:"保存成功",type:'success'})
          }
        })

      }
    },
    getSearchData() {
      if (this.searchFormId || this.searchTemplet) {
       // console.log(this.$refs.searchfrom.getData4Search());
        let data= this.$refs.searchfrom.getData4Search();
        //if(this.beforeSearch && !this.$_.isEmpty(data)){
        if(this.beforeSearch){
          data=this.beforeSearch(data,this);
        }
        return data;
      }
      return {};
    },
    search() {
      this.$refs[this.xGrid].commitProxy("query");
    },
    resetSearch(){
      this.$refs.searchfrom.reset();
    },
    dicFormater({ cellValue, row, column }) {
      if (_.isEmpty(cellValue)) return "";
      let key = column.own.props.dicFlag;
      let nm = this.$dicManager.getName(key, cellValue);
      if(this.settings.formatters && this.settings.formatters[column.property]){
        nm=this.settings.formatters[column.property]({cellValue:cellValue,row:row,column:column,name:nm});
      }
      return nm;
    },
    initGriData(val) {
      if (this.sortable) this.sortable.destroy();
      val.settings = _.isEmpty(val.settings) ? {} : val.settings;

      // 对options的数据进行封装
      this.initOptions(this, val);
      // 对settings的数据进行封装
      this.initSetting(this, val.settings);
    },
    setTableData(data) {
      this.tableData = data;
    },
    initSetting(that, settings) {
      _.forEach(settings, function(value, key) {
        that.settings[key] = value;
      });
    },
    initRowDrop() {
      this.$nextTick(() => {
        let xTable = this.$refs[this.xGrid];
        let t=this;
        this.sortable = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".vxe-body--row",
            onEnd: ({ newIndex, oldIndex }) => {
              let currRow = xTable.tableData.splice(oldIndex, 1)[0];
              xTable.tableData.splice(newIndex, 0, currRow);
              xTable.syncData();
              // if(t.options.isIndex){
              // for(let i=0;i<xTable.tableData.length;i++){
              //   if(xTable.tableData[i].NO)
              //   xTable.tableData[i].No=i+1;
              // }
              // }
              this.$emit("afterSort", {
                g: xTable,
                newIndex: newIndex,
                oldIndex: oldIndex
              });
            }
          }
        );
      });
    },
    setLockColumnable(lock){
      if(lock===true ||lock===false){
        if(lock){
          this.settings.tableColumn=this.$_.cloneDeep(this.settings._tableColumn);
        }else{
          let columns=this.$_.cloneDeep(this.settings._tableColumn);
          for(let i=0;i<columns.length;i++){
            columns[i].fixed=undefined;
          }
          this.settings.tableColumn = columns;
        }
      }
    },
    initOptions(that, val) {
      if (!_.isEmpty(val.options)) {
        let opt = that.options;
        that.options = _.assign(that.options, val.options); ///.isIndex=val.isIndex||false;
        if(val.options.searchConfig){
          that.searchConfig=val.options.searchConfig;
        }
        this.autoLoad=val.options.autoLoad==undefined?true:val.options.autoLoad;
        opt.tableToolbar = _.isEmpty(opt.tableToolbar) ? {} : opt.tableToolbar;

        let tools = [];
        _.forEach(opt.tableToolbar, function(value, key) {
          if (key === "buttons" && opt.shieldBtn === false) {
            let arr = [];
            if (opt.useDefaultButtons) arr = that.settings.tableToolbar.buttons;
            else {
              that.settings.tableToolbar.buttons = [];
            }
            _.forEach(opt.tableToolbar.buttons, function(value2, key2) {
              const index = _.findIndex(
                that.settings.tableToolbar.buttons,
                data => data.code === value2.code
              );
              if (index === -1) {
                arr.push(value2);
                // console.log(arr)
              } else {
                arr[index] = value2;
              }
            });
            if (!_.isEmpty(arr)) {
              that.settings.tableToolbar.buttons = [];
              _.forEach(arr, function(value, key) {
                // console.log(arr)d
                that.settings.tableToolbar.buttons.push(value);
              });
            }
          } else {
            that.settings.tableToolbar[key] = value;
          }
        });
        let exporti=that.settings.tableToolbar.buttons.indexOf("export");
        let exportbtn={
            id:'grid_export',
            name:'导出',
            handler:this.exportExcel
          };
        if(exporti!=-1){
          this.settings.tableToolbar.buttons[exporti]=exportbtn;
        }else if((exporti=this.settings.tableToolbar.tools.indexOf("export"))!=-1){
          this.settings.tableToolbar.tools[exporti]=exportbtn;
        }else if(this.settings.tableToolbar.export===true){
          this.settings.tableToolbar.tools[this.settings.tableToolbar.tools.length-1]=exportbtn;
        }
      }
    },
    exportExcel(queryParams_){
      let searchdata = this.getSearchData();
      let settings = this.settings;
      let _queryParams="TEMPLET";
      if(queryParams_){
        _queryParams = "FORM";
        searchdata = Object.assign(searchdata,queryParams_);
      }
      let sort=this.$refs[this.xGrid].sortData;
      const queryParams = Object.assign(
        {
          orderField: sort.property,
          order: sort.order
        },
        this.tableForm,
        settings.params,
        queryParams_
      );
      if(this.settings.beforeLoad){
          searchdata=this.settings.beforeLoad(searchdata);
      }
        let voParam = { ...searchdata };
      this.$_.extend(
        voParam,
        this.tableForm,
        settings.params,
        queryParams
      );
      fileDownload("gridExportExcel",{
        param:{flag:this.settings.flag,templet: this.settings.templet},
        voParam:voParam,
      })
    },
    getTableColumn(isInit) {
      isInit = true;
      let $t = this;
      console.log("flag:"+this.settings.flag+",queryTemplet:"+this.settings.queryTemplet);
      
      if (this.settings.flag || this.settings.templet) {
        request({
          url: this.settings.templateCfgUrl,
          data: { flag: this.settings.flag, templet: this.settings.templet, isInit: isInit },
          method: "post"
        }).then(data => {
          let queryForm = data.queryForm;

          let queryTemplet = this.settings.queryTemplet;
          if(_.isEmpty(queryTemplet))
            queryTemplet = data.queryTemplet;

          if (!_.isEmpty(queryForm) || !_.isEmpty(queryTemplet)) {
            if (!_.isEmpty(queryForm))
              $t.searchFormId = queryForm;
            else if(!_.isEmpty(queryTemplet))
              $t.searchTemplet = queryTemplet;
            if(this.searchConfig && this.searchConfig.remotFunc){
              this.remotFunc=this.searchConfig.remotFunc;
            }
          }

          let objRules = {},
            fixed = this.settings.hasFixed;
          for (let s in data.tableColumns) {
            let editrules = [];
            let rules = {};
            let itemRender = data.tableColumns[s].editRender || {};
            itemRender.attrs = {};
            data.tableColumns[s].type='html';
            if (itemRender && itemRender.props && itemRender.props.dicFlag) {
              data.tableColumns[s].props = itemRender.props;
              data.tableColumns[s].itemRender = undefined;
              data.tableColumns[s].formatter = this.dicFormater;
            }else if($t.settings.formatters && $t.settings.formatters[data.tableColumns[s].field]){
              data.tableColumns[s].formatter=$t.settings.formatters[data.tableColumns[s].field]
            }
            if (itemRender && itemRender.props) {
              if (itemRender.props.type == "int") {
                itemRender.attrs.type = "number";
              }
              itemRender.props.type = itemRender.attrs.type;

              data.tableColumns[s].headerAlign = "center";
              data.tableColumns[s].align = data.tableColumns[s].align
                ? data.tableColumns[s].align
                : "center";
            }
            data.tableColumns[s].width =
              data.tableColumns[s].width > 0
                ? data.tableColumns[s].width + "px"
                : "120px";
            if (!fixed) {
              data.tableColumns[s].fixed = undefined;
            }
          }

          // $t.settings.editRules = objRules;

          if (_.isEmpty($t.settings.templet))
            $t.settings.templet = data.templet;

          if (data.queryForm) {
          }
          if(!data.tableColumns || data.tableColumns.length==0){
            this.$message({type:'warning',message:"请求列表配置错误，请刷新页面重试或联系管理员！"})
            return;
          }
          $t.tableColumnsFilter(data.tableColumns, this);
          //if(data.queryItems)
          //$t.tableSearchItemFilter(data.queryItems, this)
          //console.log('grid',$t.$refs[$t.xGrid])
          // window.grid=$t.$refs[$t.xGrid];
          if($t.autoLoad)
          $t.$refs[$t.xGrid].commitProxy("query");
          if (isInit) {
            // 处理分页信息,后端第一次获取请求时才传递分页数据
            // console.log(data)
          }
        });
      } else if (this.settings.tableColumn) {
        this.tableColumnsFilter([], this);
      }
    },
    setPageInfo(page){
      if(page){
        const{currentPage}=page
       const {pagerConfig} = this.settings;
       if(page){
         pagerConfig.userSetPage=page;
       }
      //  if(currentPage!=undefined){
      //   this.$set( this.settings.pagerConfig,"currentPage",currentPage);
      //  }
      }
    },
    refreshFirst() {
      this.$refs[this.xGrid].commitProxy("query");
    },
    refresh() {
      this.$refs[this.xGrid].commitProxy("query");
    },
    refresh4All() {
      this.refreshpage = true;
      this.$refs[this.xGrid].commitProxy("query");
    },
    queryData(queryParams) {
      this.queryParams = queryParams || {};
      this.setPageInfo({currentPage:1,})
      this.$refs[this.xGrid].commitProxy("query");
    },
    loadData(queryParam) {
       this.queryParams = queryParam || {};
      this.$refs[this.xGrid].commitProxy("query");
    },
    // 表头数据处理器
    tableColumnsFilter: function(val, that) {
      // 默认给每一条数据添加远程数据库排序
      let sortConfig=this.settings.sortConfig||{};
      let defautlsort=sortConfig.defaultSort;
      _.forEach(val, data => {
        if(defautlsort&& defautlsort.field == data.field){
          data.sortable=true;
          data.sortBy=defautlsort.order||'asc';
        }
        data["remoteSort"] = true;
      });
      let columns = [];
      if (that.settings.expandCol) {
        columns.push(that.settings.expandCol);
      }
      // for(let i=0;i<this.settings.tableColumn.length;i++){
      //   that.settings.tableColumn[i].fixed='left';
      // }
      that.settings.tableColumn = _.concat(that.settings.tableColumn, val);
      let opt = that.options;
      // that.settings.tableColumn = [];
      let fixed = this.settings.hasFixed ? "left" : "";
      if (opt.isIndex) {
        columns.push({
          type: "seq",
          title: "序号",
          width: 60,
          fixed: fixed,
          field: "NO",
          align: "center"
        });
      }
      switch (opt.checkType) {
        case "no":
          break;
        case "check":
          columns.push({
            type: "checkbox",
            width: 60,
            align: "center",
            fixed: fixed,
            field: "CH"
          });
          break;
        case "radio":
          columns.push({
            type: "radio",
            width: 60,
            align: "center",
            fixed: fixed
          });
          break;
      }
      if (that.settings.tableColumn && that.settings.tableColumn.length > 0) {
        columns.push(...that.settings.tableColumn);
      }
      that.settings.tableColumn = columns;
      that.settings._tableColumn=this.$_.cloneDeep(columns);
      // 把远程获取的表头数据到当前
      if (that.settings.operations) {
        that.settings.tableColumn.push({
          field: "operations",
          title: "操作",
          // fixed:"left",
          width: 120,
          // fixed:"right",
          slots: { default: "operate" }
        });
      }
      if (this.settings.sortable) {
        this.initRowDrop();
      }
    },
    // 处理搜索项数据
    tableSearchItemFilter: function(val, that) {
      //console.log(val);
      // 必须添加$符号才能正常显示
      _.forEach(
        val,
        data => (data.itemRender.name = "$" + data.itemRender.name)
      );
      // 默认添加搜索和重置按钮
      val.push({
        span: 24,
        align: "center",
        collapseNode: false,
        itemRender: {
          name: "$buttons",
          children: [
            {
              props: {
                type: "submit",
                content: "搜索",
                status: "primary"
              }
            },
            {
              props: {
                type: "reset",
                content: "重置"
              }
            }
          ]
        }
      });
      // 设置默认查询项
      that.settings.formConfig.items = val;
      // console.log(val)
    },
    formatDate({ cellValue }) {
      return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
    },
    checkColumnMethodExtends({ column }) {
      // 修改列
      this.$emit("checkColumnMethodExtends", { column });
      if (column.property === "A02_SID") {
        return false;
      }
      if (column.property === "NO") {
        return false;
      }
      if (column.property === "CH") {
        return false;
      }
      return true;
    },
    importMethodExtends({ file }) {
      const formBody = new FormData();
      formBody.append("file", file);
      return this.$XModal.message({
        message: `成功导入 测试 条记录！`,
        status: "success"
      });
    },
    contentMethodExtends({
      items,
      row,
      rowIndex,
      $rowIndex,
      column,
      columnIndex,
      $columnIndex,
      type,
      cell,
      $event
    }) {
      // console.log('都是干嘛滴:',
      //   items, row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, type, cell, $event
      // )
    },
    remoteExportMethod({ options }) {
      // console.log('数据导出测试:', options)
      const proxyInfo = this.$refs.xGrid.getProxyInfo();
      // 传给服务端的参数
      const body = {
        filename: options.filename,
        sheetName: options.sheetName,
        isHeader: options.isHeader,
        original: options.original,
        mode: options.mode,
        pager: proxyInfo.pager,
        ids:
          options.mode === "selected" ? options.data.map(item => item.id) : [],
        fields: options.columns.map(column => {
          return {
            field: column.property,
            title: column.title
          };
        })
      };
      // console('我要开始导出了')
      // return XEAjax.post('https://api.xuliangzhan.com:10443/api/pub/export', body).then(data => {
      //     if (data.id) {
      //         this.$XModal.message({ message: '导出成功，开始下载', status: 'success' })
      //         // 读取路径，请求文件流 => 开始下载
      //         location.href = `https://api.xuliangzhan.com:10443/api/pub/export/download/${data.id}`
      //     }
      // }).catch(() => {
      //     this.$XModal.message({ message: '导出失败！', status: 'error' })
      // })
    },
    guid: function() {
      // debugger;
      const id = new SnowflakeId();
      // console.log(id.generate())
      return id.generate();
    },
    footerSpanMethodExtends({ columns, data }) {
      // console.debug('footerSpanMethodExtends')
      this.$emit("footerMethodExtends", { columns, data });
    },
    footerMethodExtends({ columns, data }) {
      // console.debug('footerMethodExtends方法')
      this.$emit("footerMethodExtends", { columns, data });
    },
    spanMethodExtends({ columns, data }) {
      // console.debug('spanMethodExtends方法钩子')
      this.$emit("footerMethodExtends", { columns, data });
    },
    toolbarButtonClickEvent(event) {
      // console.log("尝试输出", event)
      if (event.button.hasOwnProperty("handler")) {
        event.button.handler(event);
      }
    },
    checkboxChange: function(val) {
      //console.log("选中了----", val.records);
      this.$emit("checkboxRecords", val.records);
    },
    getSelected: function() {
      if (this.options.checkType == "radio")
        return this.$refs[this.xGrid].getRadioRecord();
      else if (this.options.checkType == "check")
        return this.$refs[this.xGrid].getCheckboxRecords();
      else return this.$refs[this.xGrid].getCurrentRecord();
    },
    //修改可编辑单元格方法
    activeCellMethod: function({ column }) {
      // console.log(column,columnIndex,"sefrtry")
      if (column.editRender.props.isEdit == "N") {
        return false;
      } else {
        return true;
      }
      // return true;
    },
    validEvent() {
      let that = this;
      that.$refs[that.xGrid].$refs.xTable.validate(errMap => {
        //console.log(errMap);
        if (errMap) {
          that.$XModal.message({
            status: "error",
            message: "校验不通过，有未填写项"
          });
        } else {
          that.$XModal.message({ status: "success", message: "校验成功！" });
        }
      });
    },
    dblclick(val) {
      this.$emit("dblclickrow", val.row);
    },
    getTableData() {
      return this.$refs[this.xGrid].getTableData();
    },
    celick(val) {
      this.$emit("celick", val.row);
    },
    pageChange({ type, currentPage, pageSize, $event }){
      this.$emit("pageChange");
    },
  }
};
</script>

<style lang="scss" scoped>
.tableTest {
  margin: 0.5px;
}
/*loading*/
$vxe-loading-background-color: rgba(0, 0, 0, 0);
$vxe-loading-z-index: 999;
::v-deep .vxe-loading {
  background-color: rgba(0, 0, 0, 0) !important;
}
.el-container .height_auto .grid_top_btn_box ::v-deep .el-main{
  margin-top:0;
  padding:0 0px 0 0!important;
}

</style>
